package com.atguigu.gmall.activity.api;

import com.atguigu.gmall.activity.model.SeckillGoods;
import com.atguigu.gmall.activity.service.SeckillGoodsService;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.common.result.ResultCodeEnum;
import com.atguigu.gmall.common.util.AuthContextHolder;
import org.apache.catalina.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 秒杀页面控制器
 */
@SuppressWarnings("all")
@RestController
@RequestMapping("/api/activity")
public class SeckillGoodsApiController {

    @Autowired
    private SeckillGoodsService seckillGoodsService;

    /**
     * 查询Redis中当日秒杀商品列表
     * @return
     */
    @GetMapping("/inner/seckill/findAll")
    public Result getSeckillGoodsList(){
        List<SeckillGoods> seckillGoodsList = seckillGoodsService.getSeckillGoodsList();
        return Result.ok(seckillGoodsList);
    }

    /**
     * 查询指定秒杀商品信息
     * @param skuId 商品id
     * @return 秒杀商品信息结果
     */
   @GetMapping("/inner/seckill/getSeckillGoods/{skuId}")
    public Result getSeckillGoods(@PathVariable("skuId") Long skuId){
       SeckillGoods seckillGoods = seckillGoodsService.getSeckillGoods(skuId);
       return Result.ok();
   }

    /**
     * 点击秒杀按钮前,为当前登录用户生成指定商品抢购码,避免使用非法手段抢购
     * @param request
     * @param skuId
     * @return
     */
   @GetMapping("/seckill/auth/getSeckillSkuIdStr/{skuId}")
    public Result getSeckillSkuIdStrBuyCode(HttpServletRequest request, @PathVariable("skuId") Long skuId){
       //1.获取登录用户id
       String userId = AuthContextHolder.getUserId(request);
       if(userId == null){
           return Result.fail().message(ResultCodeEnum.LOGIN_AUTH.getMessage());
       }
       //2.调用业务逻辑生成二维码
       String buyCode = seckillGoodsService.getSeckillSkuIdStrBuyCode(userId,skuId);
       return Result.ok(buyCode);
   }

    /**
     * 秒杀入队-将用户购买意向发送到消息队列
     * @param skuId 商品id
     * @param buyCode 抢购码
     * @return 返回消息队列消息结果
     */
   @PostMapping("/seckill/auth/seckillOrder/{skuId}")
    public Result seckillResultToQueue(HttpServletRequest request, @PathVariable("skuId") Long skuId,@RequestParam("skuIdStr") String buyCode){
       //1.获取当前登录用户id
       String userId = AuthContextHolder.getUserId(request);
       if(userId == null){
           return Result.fail().message(ResultCodeEnum.LOGIN_AUTH.getMessage()); //未登录
       }
       //2.调用业务层秒杀入队处理
       return seckillGoodsService.seckillResultToQueue(userId,skuId,buyCode);
   }

    /**
     * 前端定时发起请求检查当前用户商品秒杀结果
     * @param request
     * @param skuId 秒杀商品id
     * @return
     */
   @GetMapping("/seckill/auth/checkOrder/{skuId}")
    public Result checkOrderResult(HttpServletRequest request,@PathVariable("skuId") Long skuId){
       String userId = AuthContextHolder.getUserId(request);
       return seckillGoodsService.checkOrderResult(userId,skuId);
   }
}